package com.flyou.consumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@Slf4j
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("api/consumer/user/{id}")
//    @HystrixCommand(fallbackMethod = "findUserByIdFallBack") //一个方法单独使用的降级策略
    @HystrixCommand
    public String findUserById(@PathVariable("id") Long id) {
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
////        先获取第一个服务
//        ServiceInstance serviceInstance = instances.get(0);
//        String scheme = serviceInstance.getScheme();
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url= scheme + "://" + host + ":" + port + "/api/user/" + id;
//        使用负载均衡器


        if (id == 1) {
            throw new RuntimeException();
        }
        String url = "http://user-service/api/user/" + id;


        return restTemplate.getForObject(url, String.class);
    }

    /**
     * 服务降级后调用的方法
     * 请求参数和返回值需要与原方法一致
     *
     * @param id
     * @return
     */
    public String findUserByIdFallBack(Long id) {
        log.error("用户信息查询失败:{}", id);
        return "对不起，网络太拥挤了";
    }

    public String defaultFallback() {
        log.error("默认一个类的提示，全局降级提醒");
        return "默认一个类的提示，全局降级提醒";
    }
}
